/*
 Copyright 2010 Victor Mayoral Vilches
 
 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */


//
//  PruebaView.m
//  NaoRemote
//
//  Created by Victor Mayoral Vilches on 22/01/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "PruebaView.h"
#include <math.h> 

@implementation PruebaView

@synthesize imageBuffer;

static inline double radians (double degrees) {return degrees * M_PI/180;}

- (id)initWithFrame:(CGRect)frame buf:(char*)buffer{
    if (self = [super initWithFrame:frame]) {
        // Initialization code
    }
    self.imageBuffer = buffer;
    return self;
}

/*
    Esta función crea un CGImageRef (una referencia a un bitmap) que sera dibujada en el contexto
 */
CGImageRef CreateImageRef(int pixelsWide,
                          int pixelsHigh,
                          char* bitmapData)
{
    CGColorSpaceRef colorSpace;

    int             bitmapByteCount;
    int             bitmapBytesPerRow;
    
    colorSpace = CGColorSpaceCreateDeviceRGB();
    bitmapBytesPerRow   = (pixelsWide * 4);        
    bitmapByteCount     = (bitmapBytesPerRow * pixelsHigh); 
    
    CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, bitmapData, bitmapByteCount, NULL);
    
    CGImageRef ir = CGImageCreate(pixelsWide,
                                  pixelsHigh,
                                  8,
                                  32,
                                  bitmapBytesPerRow,
                                  colorSpace,
                                  kCGImageAlphaNoneSkipLast,
                                  provider,
                                  NULL,
                                  NO,
                                  kCGRenderingIntentDefault);

    if (ir== NULL)
    {
        free (bitmapData);// f the context isn’t created for some reason, frees the memory allocated for the bitmap data.
        fprintf (stderr, "CGImageRef not created!");
        return NULL;
    }
    
    CGColorSpaceRelease(colorSpace);      // Releases the color space.
                
    return ir;
}


/*
 Función para rellenar con datos el bitmap que mostraremos por pantalla
 
 */
char* CreateBitmapData(int pixelsWide,
                        int pixelsHigh, char* imageBuffer)
{
    
    char* bitmapData = malloc(pixelsHigh*pixelsWide*4);
    
    if (bitmapData == NULL)
    {
        fprintf (stderr, "Memory not allocated!");
        return NULL;
    }
    
    //Debemos de introducir manualmente el alpha (bits 24-31), es decir cada 3 bytes (en el cuarto)
    int counter = 0;
    for (int i=0; i<pixelsHigh*pixelsWide*4; i++) {
        int contador = i % 4;
        if ( contador == 3) {
            bitmapData[i] = 0xFF;   //Recuerdese que el alpha se obvia por la configuración hecha
        }
        else {
            bitmapData[i] = imageBuffer[counter];
            counter++;
        }                
    }    
    return bitmapData;
}



-(void)drawRect:(CGRect)rect{

 //Valores para kQVGA
    int pixelsWide = 320;
    int pixelsHigh = 240;

//    // Valores para kVGA
//    int pixelsWide = 640;
//    int pixelsHigh = 480;
    
    //Obtención del bitmap que se utilizara:
    
    char* bitmapData = CreateBitmapData(pixelsWide, pixelsHigh,self.imageBuffer);
    CGImageRef image = CreateImageRef(pixelsWide, pixelsHigh,bitmapData);
    CGContextRef myContext = UIGraphicsGetCurrentContext();
    
 
    // Reorient the coordinate system so that the 
    // origin is in the lower left corner of
    // the view and the y axis points "up" on the 
    // window.
    CGContextSaveGState(myContext);    
    CGContextTranslateCTM(
                          myContext, 0, 
                          pixelsWide);
    CGContextScaleCTM(myContext, 1.0, -1.0);    
    CGContextDrawImage(myContext, rect, image);
    CGContextRestoreGState(myContext);
 
    
    //    CGContextSetRGBFillColor(myContext, 1, 0, 0, 1); 
    //    CGContextFillRect(myContext, CGRectMake (0, 0, 200, 100 )); 
    //    CGContextSetRGBFillColor(myContext, 0, 1, 0, .5); 
    //    CGContextFillRect(myContext, CGRectMake (0, 0, 100, 200));
 
    //    CGContextBeginPath(ctx);
    //    CGContextAddArc(ctx,110,50,30,0,2*M_PI,1); 
    //    CGContextAddArc(ctx,210,50,30,0,2*M_PI,1); 
    //    CGContextAddArc(ctx,160,110,15,0,2*M_PI,1); 
    //    CGContextAddArc(ctx,160,210,25,0,2*M_PI,1); 
    //    CGContextFillPath(ctx);
    
}


- (void)dealloc {
    [super dealloc];
}

//Función para crear un Contexto gráfico de bitmaps. 
//CGContextRef CreateBitmapContext(int pixelsWide,
//                                  int pixelsHigh){
//    
//    
//    CGContextRef    context = NULL;
//    CGColorSpaceRef colorSpace;
//    char *          bitmapData;
//    int             bitmapByteCount;
//    int             bitmapBytesPerRow;
//
//    // Configuracion del colorSpace
//    colorSpace = CGColorSpaceCreateDeviceRGB();
//    bitmapBytesPerRow   = (pixelsWide * 4);
//    // Declares a variable to represent the number of bytes per row. Each pixel in the bitmap in this example is represented by 3 bytes; 8 bits each of red, green, blue
//    //IMPORTANTE: Hay que introducir el Alpha al final si utilizmaos la constante kCGImageAlphaNoneSkipLast
//    
//    
//    bitmapByteCount     = (bitmapBytesPerRow * pixelsHigh); //Numero total de bytes. En este caso 230400 bytes
//    
//    //    colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);// Creates a generic RGB color space. 
//    
//    bitmapData = malloc(bitmapByteCount);
//    // Calls the malloc function to create a block of memory in which to store the bitmap data. Creates a 24-bit RGB bitmap (that is, an array with 24 bits per pixel, each pixel containing 8 bits each of red, green and  blue). Each pixel in the bitmap occupies 3 bytes of memory.
//        
//    if (bitmapData == NULL)
//    {
//        fprintf (stderr, "Memory not allocated!");
//        return NULL;
//    }
//    
//    //Creates a bitmap graphics context, supplying the bitmap data, the width and height of the bitmap, the number of bits per component, the bytes per row, the color space, and a constant that specifies whether the bitmap should contain an alpha channel and its relative location in a pixel. The constant kCGImageAlphaPremultipliedLast indicates that the alpha component is stored in the last byte of each pixel and that the color components have already been multiplied by this alpha value. See “The Alpha Value” for more information on premultiplied alpha.
//    
//    context = CGBitmapContextCreate (bitmapData,
//                                     pixelsWide,
//                                     pixelsHigh,
//                                     8,      // bits per component
//                                     bitmapBytesPerRow,
//                                     colorSpace,
//                                     kCGImageAlphaNoneSkipLast);
//    if (context== NULL)
//    {
//        free (bitmapData);// f the context isn’t created for some reason, frees the memory allocated for the bitmap data.
//        fprintf (stderr, "Context not created!");
//        return NULL;
//    }
//    
//    CGColorSpaceRelease(colorSpace);      // Releases the color space.
//    
//    for (int i=0; i<bitmapByteCount; i++) {
//        bitmapData[i] = rand()%256;
//    }
//    
//    return context;
//}
//

@end
